// IDSetter.cpp : Defines the entry point for the console application.
//

/*
#define ID_NAME1 IDNO1
#define ID_NAME2 IDNO2
*/

#include "stdafx.h"
#include <fstream>
#include <string>
using namespace std;

const char IDDEFINESTART[] = "#define";
static const int MAX_IDNAME_LEN = 1024;

template<typename CHARTYPE>
bool IsSpace(CHARTYPE _ch)
{
	return _ch == ' ' ||
		_ch == '\t';
}

template<typename CHARTYPE>
bool GetTitleAndIDInString(const CHARTYPE* _pstr, CHARTYPE* _ptitle, int& _id, const CHARTYPE*& _pleftstr,
	const CHARTYPE* _pStartWith)
{
	//start with
	while (*_pstr && *_pStartWith)
	{
		*_ptitle++ = *_pstr;
		if (IsSpace(*_pstr))
		{
			++_pstr;
			continue;
		}
		if (*_pstr == *_pStartWith)
		{
			++_pstr;
			++_pStartWith;
		}
		else
		{
			return false;
		}
	}

	if (*_pStartWith == 0 && (IsSpace(*_pstr)))
	{
		//name
		bool bname = false;
		while (*_pstr)
		{
			*_ptitle++ = *_pstr;
			if (IsSpace(*_pstr))
			{
				if (bname)
				{
					++_pstr;
					break;
				}
			}
			else
			{
				bname = true;
			}
			++_pstr;
		}
		
		while (*_pstr && IsSpace(*_pstr))
		{
			*_ptitle++ = *_pstr;
			++_pstr;
		}
		*_ptitle = 0;

		//id
		int nsign = 1;
		_id = 0;
		if (*_pstr == '-')
		{
			nsign = -1;
			++_pstr;
		}
		while (*_pstr)
		{
			if (*_pstr >= '0' && *_pstr <= '9')
			{
				_id = _id * 10 + (*_pstr - '0');
			}
			else
			{
				break;
			}
			++_pstr;
		}

		_id *= nsign;

		//left
		_pleftstr = _pstr;
		return true;
	}

	return false;
}
template<typename CHARTYPE = char>
int NormalProcess(const _TCHAR* _strSource, const _TCHAR* _strTarget, const CHARTYPE* _pStartWith)
{
	ifstream ifs;
	ofstream ofs;
	ifs.open(_strSource, ios::in);
	string strread;
	if (ifs.is_open())
	{
		ofs.open(_strTarget, ios::out);
		if (ofs.is_open())
		{
			int nnextid = -1, nlastid;
			int nid;
			CHARTYPE title[MAX_IDNAME_LEN];
			const CHARTYPE* strleft;
			while (getline(ifs, strread))
			{
				if (GetTitleAndIDInString((CHARTYPE*)strread.c_str(), title, nid, strleft, _pStartWith))
				{
					if (nnextid < 0)
					{
						if (nid > 0)
						{
							nnextid = nid;
						}
						else
						{
							nnextid = 100;
						}
						nlastid = nnextid;
					}
					else if (nid > nlastid + 10)
					{
						nnextid = nid;
						nlastid = nid;
					}
					else if (nid > 0 && nid < nlastid - 10)
					{
						nnextid = nid;
						nlastid = nid;
					}
					else if (nid > 0)
					{
						nlastid = nid;
					}

					ofs << title << nnextid << strleft << "\n";

					++nnextid;
				}
				else
				{
					ofs << strread << "\n";
				}

			}
			ofs.close();
		}
		ifs.close();
	}
	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	NormalProcess(_T("e:\\ra.txt"), _T("e:\\out"), IDDEFINESTART);
	return 0;
}

